package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.MenuItemCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.UserMessageBean;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.UserMessageParser;
import com.elinkway.infinitemovies.http.requesttask.RequestUserUpdateTask;
import com.elinkway.infinitemovies.utils.ImageUploadUtil;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.view.CircleImageView;
import com.elinkway.infinitemovies.view.CustomDialog;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

public class UserMessageActivity extends BaseSecondaryActivity implements OnClickListener, ImageUploadUtil.OnUploadProcessListener{

    public static final String TAG = "UserMessageActivity";
    private RelativeLayout mAvatarContainer;
    private RelativeLayout mnickNameContainer;
    private RelativeLayout mSexContainer;
    private RelativeLayout mPhoneContainer;
    private CircleImageView mAvatar;
    private TextView mNickName;
    private TextView mSex;
    private TextView mPhoneNum;
    private Button mLogoutContainer;

    private final int nickNameRequestNum = 1001;
    private final int sexRequestNum = 1002;
    private final int photoSelect = 1003;
    private final int cameraPhoto = 1004;
    public final int PHOTO_RESOULT = 1005;
    public final static String NICKNAME = "nickname";
    public final static String SEX = "sex";

    private RequestUserMessageTask mRequestUserMessageTask;
    private RequestLogoutTask mRequestLogoutTask;

    private SharedPreferences mLoginSp;
    private UserMessageBean mUserMessage;
    private CustomDialog.Builder mLogoutDialogBuilder;
    private CustomDialog.Builder mAvatarSelectDialogBuilder;
    private CustomDialog mLogoutDialog;
    private CustomDialog mAvatarSelectDialog;

    private Bitmap mAvatarBitMap;
    private String avatarPath;

    public static final int USER_MESSAGE_CODE = 222;
    public static final int LOGIN_OUT_CODE = 223;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setActionBarActivityClassName(TAG);
        setContentView(R.layout.activity_user_message);
        initActionBar();
        mTitleTv.setText(getResources().getString(R.string.user_msg));
        initView();
        setListener();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.user_message, menu);
        MenuItem item = menu.findItem(R.id.action_sure);
        item.setVisible(false);
        View mView = MenuItemCompat.getActionView(item);
        mView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        return true;
    }

    private void initView() {
        mAvatarContainer = (RelativeLayout) findViewById(R.id.avatar_container);
        mnickNameContainer = (RelativeLayout) findViewById(R.id.nickname_container);
        mSexContainer = (RelativeLayout) findViewById(R.id.sex_container);
        mPhoneContainer = (RelativeLayout) findViewById(R.id.phone_container);
        mAvatar = (CircleImageView) findViewById(R.id.avatar);
        mAvatar.setImageResource(R.drawable.avatar_default);
        mNickName = (TextView) findViewById(R.id.nickname);
        mSex = (TextView) findViewById(R.id.sex);
        mPhoneNum = (TextView) findViewById(R.id.phone_num);
        mLogoutContainer = (Button) findViewById(R.id.logout);
        mLoginSp = getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
        if(getIntent() != null){
            String headerIcon = getIntent().getStringExtra("headerIcon");
            if(!TextUtils.isEmpty(headerIcon)){
                ImageLoader.getInstance().displayImage(headerIcon, mAvatar);
            }
            mNickName.setText(getIntent().getStringExtra("userName"));
            String sex = getIntent().getStringExtra("userSex");
            if("0".equals(sex)) {
                mSex.setText("男");
            }else if("1".equals(sex)) {
                mSex.setText("女");
            }else if("2".equals(sex)) {
                mSex.setText("保密");
            }
        }
        mRequestUserMessageTask = new RequestUserMessageTask(UserMessageActivity.this, mLoginSp.getString(LoginActivity.TOKEN, ""));
        mRequestUserMessageTask.start();
        initDialog();
    }

    private void initDialog() {
        mLogoutDialogBuilder = new CustomDialog.Builder(this);
        mLogoutDialogBuilder.setMessage(getResources().getString(R.string.logout_tip));
        mLogoutDialogBuilder.setPositiveButton(R.string.logout_sure, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                mRequestLogoutTask = new RequestLogoutTask(UserMessageActivity.this, mLoginSp.getString(LoginActivity.TOKEN, ""));
                mRequestLogoutTask.start();
                MoviesConstant.isRefreshMyFragment = true;
                dialog.dismiss();
            }
        });
        mLogoutDialogBuilder.setNegativeButton(R.string.logout_cacel, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        mLogoutDialog = mLogoutDialogBuilder.create();

        mAvatarSelectDialogBuilder = new CustomDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.avatar_dialog, null);
        view.findViewById(R.id.phone_img_select).setOnClickListener(this);
        view.findViewById(R.id.phone_camera).setOnClickListener(this);
        view.findViewById(R.id.cancel).setOnClickListener(this);
        mAvatarSelectDialogBuilder.setContentView(view);
        mAvatarSelectDialog = mAvatarSelectDialogBuilder.create();
    }

    private void setListener() {
        mAvatarContainer.setOnClickListener(this);
        mnickNameContainer.setOnClickListener(this);
        mSexContainer.setOnClickListener(this);
        mLogoutContainer.setOnClickListener(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                case nickNameRequestNum:
                    String nickname = data.getExtras().getString(NICKNAME);
                    mNickName.setText(nickname);
                    mUserMessage.setNick_name(nickname);
                    break;
                case sexRequestNum:
                    String sex = data.getExtras().getString(SEX);
                    mSex.setText(sex);
                    break;
                case photoSelect:
                    Uri selectedImage = null;
                    if(data != null && data.getData() != null) {
                        selectedImage = data.getData();
                    }else {
                        ToastUtil.showShortToast(this, "获取图片失败");
                        return;
                    }

                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    String picturePath = null;
                    if(cursor == null){
                        if(selectedImage != null && selectedImage.toString().startsWith("file://")&& selectedImage.toString().contains("Camera")){
                            picturePath = selectedImage.toString().substring(7);
                        }
                    }else{
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        picturePath = cursor.getString(columnIndex);
                        cursor.close();
                    }
                    CropUserPortraitActivity.copyFile(picturePath, avatarPath);
                     //启动裁剪页面
                    Intent mIntent = new Intent(this,
                            CropUserPortraitActivity.class);
                    mIntent.putExtra("thumbnail", picturePath);
                    startActivityForResult(mIntent, PHOTO_RESOULT);
                    break;

                case cameraPhoto:
                    Intent cameraPhotoIntent = new Intent(this,
                            CropUserPortraitActivity.class);
                    cameraPhotoIntent.putExtra("thumbnail", avatarPath);
                    startActivityForResult(cameraPhotoIntent, PHOTO_RESOULT);
                    break;

                case PHOTO_RESOULT:
                    String code = data.getExtras().getString("code");
                    String msg = data.getExtras().getString("msg");
                    String newImgUrl = data.getExtras().getString(CropUserPortraitActivity.NEWIMGURL);
                    if("200".equals(code)){
                        if(!TextUtils.isEmpty(newImgUrl)){
                            RequestUserUpdateTask mRequestUserUpdateTask = new RequestUserUpdateTask(UserMessageActivity.this, "", "", newImgUrl);
                            mRequestUserUpdateTask.start();
                            ImageLoader.getInstance().displayImage(newImgUrl, mAvatar);
                            if(mAvatarSelectDialog != null) {
                                mAvatarSelectDialog.dismiss();
                            }
                        }
                    }else{
                        if(TextUtils.isEmpty(msg)){
                            ToastUtil.showShortToast(UserMessageActivity.this, "上传失败");
                        }else{
                            ToastUtil.showShortToast(UserMessageActivity.this, msg);
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.avatar_container:
                UmengEventPoster.doEventPost(UmengEventPoster.EDIT_AVATAR);
                if(mAvatarSelectDialog != null) {
                    mAvatarSelectDialog.getWindow().setGravity(Gravity.BOTTOM);
                    mAvatarSelectDialog.show();
                    avatarPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ysdq" + "/Pictures" + "/portrait_"
                            + System.currentTimeMillis() + ".png";
                }
                break;
            case R.id.nickname_container:
                UmengEventPoster.doEventPost(UmengEventPoster.EDIT_NICKNAME);
                if (mUserMessage != null) {
                    Intent nickNameIntent = new Intent(UserMessageActivity.this, NicknameModifyActivity.class);
                    nickNameIntent.putExtra(NicknameModifyActivity.NICKNAME, mUserMessage.getNick_name());
                    startActivityForResult(nickNameIntent, nickNameRequestNum);
                }
                break;
            case R.id.sex_container:
                UmengEventPoster.doEventPost(UmengEventPoster.EDIT_GENDER);
                if (mUserMessage != null) {
                    Intent sexIntent = new Intent(UserMessageActivity.this, SexModifyActivity.class);
                    sexIntent.putExtra(SexModifyActivity.GENDER, mUserMessage.getSex());
                    startActivityForResult(sexIntent, sexRequestNum);
                }
                break;
            case R.id.logout:
                if(mLogoutDialog != null) {
                    mLogoutDialog.show();
                }
                break;
            case R.id.phone_img_select:
                doSelectImageFromLoacal();
                break;
            case R.id.phone_camera:
                try {
                    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        Intent tPIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        tPIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                        File file = new File(avatarPath);
                        if (!file.exists())
                            file.getParentFile().mkdirs();
                        tPIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(avatarPath)));
                        startActivityForResult(tPIntent, cameraPhoto);
                    }else {
                        ToastUtil.showShortToast(this, "内存卡不存在");
                    }

                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.cancel:
                mAvatarSelectDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLogoutDialogBuilder != null) {
            mLogoutDialogBuilder = null;
        }
    }

    private void doSelectImageFromLoacal(){
        Intent localIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        localIntent.setType("image/*");
        startActivityForResult(localIntent, photoSelect);
    }

    public static void launch(Activity activity) {
        Intent intent = new Intent(activity, UserMessageActivity.class);
        activity.startActivityForResult(intent, USER_MESSAGE_CODE);
    }

    @Override
    public void onUploadDone(int responseCode, String message) {

    }

    @Override
    public void onUploadProcess(int uploadSize) {

    }

    @Override
    public void initUpload(int fileSize) {

    }

    public class RequestUserMessageTask extends MoviesHttpAsyncTask<UserMessageBean> {

        private String token;

        @Override
        public void netNull() {
            super.netNull();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
        }

        public RequestUserMessageTask(Context context, String token) {
            super(context);
            this.token = token;
        }

        @Override
        public LVideoDataHull<UserMessageBean> doInBackground() {
            LVideoDataHull<UserMessageBean> ret = MoviesHttpApi.userMessageRequest(
                    new UserMessageParser(), token);
            return ret;
        }

        @Override
        public void onPostExecute(int updateId, UserMessageBean result) {
            mUserMessage = result;
            mNickName.setText(result.getNick_name());
            int gender = Integer.valueOf(result.getSex());
            if(gender == 0) {
                mSex.setText("男");
            }else if(gender == 1) {
                mSex.setText("女");
            }else if(gender == 2) {
                mSex.setText("保密");
            }
            if("".equals(result.getPhone_num())) {
                mPhoneContainer.setVisibility(View.GONE);
            }else {
                mPhoneContainer.setVisibility(View.VISIBLE);
                mPhoneNum.setText(result.getPhone_num());
            }
            ImageLoader.getInstance().displayImage(mUserMessage.getImg_url(), mAvatar);
        }
    }

    public class RequestLogoutTask extends MoviesHttpAsyncTask<UserMessageBean> {

        private String token;

        @Override
        public void netNull() {
            super.netNull();
            clearUser();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            clearUser();
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
            clearUser();
        }

        public RequestLogoutTask(Context context, String token) {
            super(context);
            this.token = token;
        }

        @Override
        public LVideoDataHull<UserMessageBean> doInBackground() {
            LVideoDataHull<UserMessageBean> ret = MoviesHttpApi.logoutRequest(
                    new UserMessageParser(), token);
            return ret;
        }

        @Override
        public void onPostExecute(int updateId, UserMessageBean result) {
            clearUser();
            MoviesConstant.isRefreshMyFragment = true;
        }
    }

    private void clearUser(){
        SharedPreferences.Editor editor = mLoginSp.edit();
        editor.putString("loginType", "");
        editor.putString("openId", "");
        editor.putString(LoginActivity.TOKEN, "");
        editor.putString(LoginActivity.UID, "");
        editor.commit();
        new PlayRecordDao(MoviesApplication.getInstance()).deleteServerAll();
        setResult(LOGIN_OUT_CODE);
        UserMessageActivity.this.finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
}
